package jp.ac.u_tokyo.dch.util.common;

import java.util.Collections;
import java.util.List;

import jp.ac.u_tokyo.dch.model.output.XmlComposite;
import jp.ac.u_tokyo.dch.model.output.XmlData;
import jp.ac.u_tokyo.dch.util.LevelComparator;

public class XmlOutputUtil {


	public static void reflash(List<XmlData> reflashList) {

		int size = reflashList.size();

		for (int i = 0; i < size; i++) {

			reflashList.get(i).setIndex(String.valueOf(i));
		}

	}

	public static void fillList(List<XmlData> xmlObjList) {


		for (int i = 0; i < xmlObjList.size(); i++) {

			if (xmlObjList.get(i) == null) {
				xmlObjList.remove(i);
				i--;
			}
		}

	}

	/**
	 *
	 * @return
	 */
	public static XmlComposite xmlObjListToXmlDisObj(List<XmlData> xmlDataList) {

		XmlOutputUtil.fillList(xmlDataList);

		XmlOutputUtil.reflash(xmlDataList);

		Collections.sort(xmlDataList, new LevelComparator());

		XmlData xmlObj = xmlDataList.get(0);

		XmlComposite xmlDisObj = new XmlComposite(Integer.valueOf(xmlObj.getTagId()), 0, Integer.valueOf(xmlObj.getIndex()), xmlObj.getTagName(), xmlObj.getType());

		int size = xmlDataList.size();

		for (int i = 1; i < size; i++) {

			XmlData childXmlObj = xmlDataList.get(i);

			xmlDisObj.addChild(Integer.valueOf(childXmlObj.getTagId()), Integer.valueOf(childXmlObj.getOyaTagId()), Integer.valueOf(childXmlObj.getIndex()), childXmlObj.getTagName(), childXmlObj.getType());
		}

		return xmlDisObj;
	}

	/**
	 *
	 * @return
	 */
	public static XmlComposite xmlObjListToXmlDisObjForOutput(List<XmlData> xmlDataList) {

		XmlOutputUtil.fillList(xmlDataList);

		XmlOutputUtil.reflash(xmlDataList);

		Collections.sort(xmlDataList, new LevelComparator());

		XmlData xmlObj = xmlDataList.get(0);

		XmlComposite xmlDisObj = new XmlComposite(Integer.valueOf(xmlObj.getTagId()), 0, Integer.valueOf(xmlObj.getIndex()), xmlObj.getTagName(), xmlObj.getType(), xmlObj.getAttrList(), xmlObj.getText());

		int size = xmlDataList.size();

		for (int i = 1; i < size; i++) {

			XmlData childXmlObj = xmlDataList.get(i);

			xmlDisObj.addChild(Integer.valueOf(childXmlObj.getTagId()), Integer.valueOf(childXmlObj.getOyaTagId()), Integer.valueOf(childXmlObj.getIndex()), childXmlObj.getTagName(), childXmlObj.getType(), childXmlObj.getAttrList(), childXmlObj.getText());
		}

		return xmlDisObj;
	}
}
